<?php 
/* @version $Id: admin.joomleague.php 1201 2008-07-08 16:08:26Z julienv $
 * @package Joomleague  
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *   
 * JoomLeague League Management and Prediction Game for Joomla!
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 
?>

<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

// for joomla 1.5 compatibity, all the component variables we will use as global must be 
// explicitely declared as so, before they are used
global $project, $jlgConfig, $team, $cid, $gid, $round, $task, $act, $joomleague_team, $round;

//require_once( $mainframe->getPath( 'admin_html' ) );


//##########################################################################################################################
// Sprachauswahl Start
require_once $mainframe->getPath( 'class' );
require_once $mainframe->getPath( 'front_html' );

if (file_exists(JL_ADMIN_PATH.'/lang/'._JL_LANG.'.php')) {
  include(JL_ADMIN_PATH.'/lang/'._JL_LANG.'.php');
} 
else{
  include(JL_ADMIN_PATH.'/lang/english.php');
}
if (file_exists(JL_FRONTEND_PATH.'/language/'._JL_LANG.'.php')) {
  include(JL_FRONTEND_PATH.'/language/'._JL_LANG.'.php');
} 
else{
  include(JL_FRONTEND_PATH.'/language/english.php');
}

// config file
include_once(JL_ADMIN_PATH."/jlgconfig.php" );

// Sprachauswahl Ende
//##########################################################################################################################

$jl_v = new JoomLeagueVersion();
$joomleague_version = $jl_v->version;
define('JL_VERSION', $joomleague_version);

//$cid = mosGetParam($_POST, 'cid', array(0));
$cid = mosGetParam($_REQUEST, 'cid', array(0));
$gid = mosGetParam($_REQUEST, 'gid', '0');

$option = mosGetParam($_REQUEST , 'option' , 'com_joomleague');

$act = mosGetParam($_REQUEST , 'act' , '');
if ($act=='') $act = (JL_ADMIN_MODE == 'league_management') ? 'projects' : 'predictions'; //projects,clubs,teams,seasons etc

$task = mosGetParam($_REQUEST , 'task' , ''); //new,edit,save,delete etc
include_once( "includes/pageNavigation.php" );
$round = intval(mosGetParam($_REQUEST,'round', 0)); 
$tab = "tab1"; //matrix

if(substr($task,0,3) == "tab"){
  $tab = $task;
  $task = "matrix";
}

if (!is_array($cid)){
  $cid = array(0);
}

if($act == 'projects' && $task == 'setactual'){
  $_SESSION["joomleague"] = $cid[0];
  session_unregister("joomleague_team");
  session_unregister("joomleague_match");
  //setCookie('joomleague', $cid[0]);
  //mosRedirect(JL_ADMIN_COMPONENT_LINK);
}

$project = null;
$team = null;

//$joomleague = intval(mosGetParam($_COOKIE, 'joomleague', 0));
$joomleague = intval(mosGetParam($_SESSION, 'joomleague', 0));

if($joomleague > 0){
  $project = new JoomLeague($database);
  $project->load($joomleague);
}

if($act == 'teamtool' && $task == 'setactual'){
  if (mosGetParam($_REQUEST, 'mypp', 0) > 0) $_SESSION["joomleague"] = mosGetParam($_REQUEST, 'mypp', 0);
  $_SESSION["joomleague_team"] = $cid[0];
  //setCookie('joomleague_team', $cid[0]);
  mosRedirect(JL_ADMIN_COMPONENT_LINK.'&act=playertool');
}

if($act == 'matches' && $task == 'event'){
  $_SESSION["joomleague_match"] = $cid[0];
  //setCookie('joomleague_match',$cid[0]);
  mosRedirect(JL_ADMIN_COMPONENT_LINK.'&act=matchevents');
}

//$joomleague_team = intval(mosGetParam($_COOKIE, 'joomleague_team', 0));
$joomleague_team = intval(mosGetParam($_SESSION, 'joomleague_team', 0));
if($joomleague_team > 0){
  $tl = new TeamTool($database);
  $tl->load($joomleague_team);
  
  $team = new JL_Team( $database );
  $team->load($tl->team_id);
}

$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
define ( 'JL_ACTION', $act );

// new for prediction separation
if (JL_ADMIN_MODE == 'prediction_management') {
  
  switch($act){
  
    case 'predictions':
      require JL_ADMIN_PATH.'/lib/inc.prediction.php';
      switch($task){
        case 'new':
        case 'edit':
         jl_prediction_show ($cid[0], $task ,$my);
        break;
        case 'save':
        case 'apply':
          jl_prediction_save ($task);
        break;
        case 'cancel':
          jl_prediction_cancel ($task);
        break;
        case 'publish':
          jl_prediction_publish($cid, $my, 1);
        break;
        case 'unpublish':
          jl_prediction_publish($cid, $my, 0);
        break;
        case 'remove':
          jl_prediction_remove($cid);
        break;
        default:
          jl_prediction_list($limit, $limitstart, $my);
        break;
      }
    break;
    case 'prediction_users':
      $project_id = $mainframe->getUserStateFromRequest( "project{".JL_OPTION."}", 'project_id', 0 );
      require JL_ADMIN_PATH.'/lib/inc.prediction_users.php';
      switch($task){
        case 'send':
          jl_pred_user_sendmail($project_id);
        break;
        case 'approve':
          jl_pred_user_approve($cid, 1);
        break;
        case 'reject':
          jl_pred_user_approve($cid, 0);
        break;
        case 'remove':
          jl_pred_user_remove($cid);
        break;
        default:
          jl_pred_user_list($project_id, $limit, $limitstart);
        break;
      }
    break;
    case 'prediction_setting':
      $sid = intval(mosGetParam($_REQUEST, 'sid', $cid[0]));
      require JL_ADMIN_PATH.'/lib/inc.prediction_setting.php';
      switch($task){
        case 'edit':
          jl_pred_setting_show ($sid, $task ,$my);
        break;
        case 'save':
        case 'apply':
          jl_pred_setting_save ($sid, $task);
        break;
        case 'cancel':
          jl_pred_setting_cancel ($sid);
        break;
      }
    break;
  }
}
// new for prediction separation ENDS
else {
switch($act){

  case 'JLimport':
    jlImport();
    break;
  
  case 'config':
		switch($task){
			case 'apply':
			case 'save':
        saveconfig( $option );
        break;
			case 'edit':
			default:
        showconfig( $option );
        break;
    }
    break;
        
  case 'template_config':
		switch($task){
		  case 'reset':
  			template_config_reset($cid , $option);
  			break;
			case 'apply':
        template_config_apply();
			break;
			case 'save':
        template_config_save();
        break;
			case 'edit':
        template_config_edit($cid);
        break;
			case 'cancel':
        template_config_cancel();        
        break;
      case 'import':
        template_config_import($project->id);
        break;
			default:
        template_config_show();
        break;
    }
    break;
     
	case 'countries':
    switch($task){
    	case 'new':
      case 'edit':
        $row = new Country( $database );
        $row->load( $cid[0] );
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This item was checked out');
        }
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_countries.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';
      break;
      case 'unpublish';
        $row = new Country( $database );
        $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      case 'publish':
        $row = new Country( $database );
        $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      case 'save':
        $row = new Country( $database );
        $row->bind( $_POST );
        $row->save($_POST, "");
	    	$row->checkin();
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      case 'cancel':
        $row = new Country( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.countries_iso_code_3) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_countries AS a"
                          . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );

        $countries = array();
        $query="SELECT * FROM #__joomleague_countries AS a"
		      . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
			   " ORDER BY published DESC, countries_iso_code_3 LIMIT $pageNav->limitstart,$pageNav->limit";
				
        $database->setQuery($query);
        $rows = $database->loadObjectList();
       
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_countries.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
      }
  break;
  
	case "editEvents":
      $regular_output = false;
      
			// check edit rights
      if( $my->id == $project->joomleague_admin 
       || $my->id == $project->joomleague_editor 
       || $my->gid > 1 )
      { 
        $mytask = mosGetParam($_REQUEST, "mytask",'');       
        $mid    = intval( mosGetParam( $_REQUEST, "mid", 0 ) ); 
      	$match = new Match($database);
        $match->load($mid);        
        
        require JL_FUNCTIONS_PATH.'/editevents.class.php';
        $eved = new jl_EditEvents($project, $match, true);
        
        switch($mytask) 
        {
          case "showevents":
            $eved->showEvents('block');
            break;
          case "saveevent":
            $eved->saveMatchEvent();
            $eved->showEvents('block');
          break;
          case "deleteevent":
            $eved->deleteMatchEvent();
            $eved->showEvents('block');
          break;
          case "updateevent":
            $eved->updateMatchEvent();
            $eved->showEvents('block');
            break;
          case "editsquad":
            $eved->editSquad('block', 'block', 'none');
            break;
          case "savesquads":
            $eved->saveSquad();
            $eved->editSquad('block', 'block', 'block');
            break;                        
          case "updatesubst":
            $eved->updateSubst();
            $eved->editSquad('block', 'block', 'block');
            break;
          
          default:
            $eved->showEventsNav();
        }
      }
      else echo "<span style='color:#ff0000;'><b>YOU ARE NOT ALLOWED!!!<br /></span>";
      break;
      // Event Editing mode ends here
      	
  case "editmatch":
		$mytask=mosGetParam($_REQUEST, "mytask", '');
		$mid=intval(mosGetParam($_REQUEST, "mid", 0));
		
    if(    $my->id == $project->joomleague_admin 
        || $my->id == $project->joomleague_editor 
        || $my->usertype == 'Administrator' 
        || $my->usertype == 'Super Administrator') {
			$match = new Match($database);
		 	$match->load($mid);
			
		 	switch ($mytask) {
				case "cancel":
			  	$match->checkin( $mid );
					break;
				case "load":
					if (is_null($match->playground_id)) {
						$homteamtoolid=$project->getTeamtool_id($match->matchpart1);
						$playgroundtt=new TeamTool($database);
						$playgroundtt->load($homteamtoolid);
						$selected_playground=$playgroundtt->standard_playground;
					}
					else $selected_playground=$match->playground_id;
					
					// playground list
					$playgrounds[] = mosHTML::makeOption( '0', jl_utf8_convert(_JL_ADMIN_SELECT_PLAYGROUND) );
	        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_playgrounds ORDER BY name");
	        if ($temp = $database->loadObjectList()) {
	         foreach($temp AS $tmp) {
	           $tmp->text = jl_utf8_convert($tmp->text);
	         }
	        }
	        $playgrounds = array_merge( $playgrounds, $temp );
	        $playgroundslist = mosHTML::selectList( $playgrounds, 'playground_id'.$match->match_id, 'class="inputbox" style="font-size:9px;" size="1"','value', 'text', $selected_playground );
				  
				  // teams dropdown
				  $teams = $project->getTeams();
				  $teamsoptions[] = mosHTML::makeOption(0,_JL_CHOOSE_TEAM);
				 	foreach ($teams AS $team) {
				 		$teamsoptions[] = mosHTML::makeOption($team->id, jl_utf8_convert($team->name));
					}
					
					// referees dropdown
				 	if ($project->teams_as_referees)
					{
					  $query = "SELECT id, name FROM #__joomleague_teams ORDER BY name";
					  $database->setQuery($query);
					  $results = $database->loadObjectList();
					  $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
					  foreach($results as $result){
					   $ref[] = mosHTML::makeOption($result->id, jl_utf8_convert($result->name));
					  }
					}
					else
					{
					  $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
					  $database->setQuery($query);
					  $results = $database->loadObjectList();
					  $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
					  foreach($results as $result){
					    $ref[] = mosHTML::makeOption($result->id, jl_utf8_convert("$result->lastname, $result->firstname"));
					  }
					}
					// load home team
					$team1 = new JL_Team($database);
          $team1->load($match->matchpart1);
          //load away team
          $team2 = new JL_Team($database);
          $team2->load($match->matchpart2);
          // ready, checkout while editing
          $match->checkout( $my->id );
			    require (JL_ADMIN_TEMPLATE_PATH.'/edit_match.tpl.php');
			    break;
      }
    }
    break;
	
  case 'updates':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_updates.tpl.php';
// new status important for new DB-Structure (possibility of revert changes - necessary?
    $status=intval(mosGetParam($_REQUEST, 'status', 0));
    switch($id){
      case 1: $view = "components/com_joomleague/updates/update_0.80_to_0.85.php";break;
      case 2: $view = "components/com_joomleague/updates/update_0.85_to_0.86.php";break;
// new case to update to introduce DB changes one round per matchday
      case 3: $view = "components/com_joomleague/updates/update_0.86_to_0.86a.php";break;
      case 4: $view = "components/com_joomleague/updates/update_0.86a_to_0.90.php";break;
      case 5: $view = "components/com_joomleague/updates/update_0.90_to_0.91.php";break;
      case 6: $view = "components/com_joomleague/updates/update_0.91_to_0.92.php";break;
      case 7: $view = "components/com_joomleague/updates/update_0.92_to_0.93.php";break;
    }
    require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
  
  break;
  
  case 'import':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_imports.tpl.php';
    
    switch($id){
      case 1: $view = "components/com_joomleague/imports/jl_buli_06_07.php";break;
      case 2: $view = "components/com_joomleague/imports/jl_events.php";break;
      case 3: $view = "components/com_joomleague/imports/jl_referees.php";break;
      case 4: $view = "components/com_joomleague/imports/jl_buli_07_08.php";break;
      case 5: $view = "components/com_joomleague/imports/jl_playgrounds.php";break;
      case 6: $view = "components/com_joomleague/imports/jl_countries.php";break;
      case 7: $view = "components/com_joomleague/imports/jl_dfbkeys.php";break;
    }
    require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
  
  break;  
  
    case 'LMOimport':
    
    $id = intval(mosGetParam($_REQUEST, 'id', 0));
    $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_lmo_import.tpl.php';
    
    switch($id){
      case 1: $view = "components/com_joomleague/imports/lmoImport.php";break;

    }
    require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
  
  break;  
  
  case 'frontend':
  
    $teams = $project->getTeams();
    
    $view = JL_ADMIN_TEMPLATE_PATH.'/edit_frontend.tpl.php';    
    require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
  
  break;
  
  case 'matches':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Match( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        //$homesquad=explode(";", trim($row->homeroster));
		    //foreach ($homesquad AS $player) $temphome[]->value = $player;
		    //$awaysquad=explode(";", trim($row->awayroster));
		    //foreach ($awaysquad AS $player) $tempaway[]->value = $player;
		    /*
		    $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          WHERE team_id = %s AND
                          pt.project_id = %s ORDER BY pos.ordering, pl.lastname",$row->matchpart1,$project->id);
        
    		$database->setQuery($query);
    		$homeplayers = $database->loadObjectList();
        foreach($homeplayers as $result){
        	$homesquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname));
        }
        $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname, pos.name AS positionname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          WHERE team_id = %s AND
                          pt.project_id = %s ORDER BY pt.position_id, pl.lastname",$row->matchpart2,$project->id);
            
    		$database->setQuery($query);
    		$guestplayers = $database->loadObjectList();
        foreach($guestplayers as $result){
        	$guestsquadoptions[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname, $result->firstname, $result->positionname)); 
        }
    */
        /*hack: referee is one other team*/
        if ($project->teams_as_referees)
        {
          $query = "SELECT id, name, short_name FROM #__joomleague_teams ORDER BY name";        	
        	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s", $result->name)); 
          }
        }
        else
        {
          $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
       	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s, %s", $result->lastname, $result->firstname)); 
          }
        }

        $refereelist = mosHTML::selectList( $ref, 'referee_id', 'class="inputbox" size="1"','value', 'text', $row->referee_id );
        unset($ref);
        
        
        $team1 = new JL_Team( $database );
        $team1->load( $row->matchpart1);
        
        $team2 = new JL_Team( $database );
        $team2->load( $row->matchpart2);
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_matches.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';    
         
      break;
      
      case 'save':
        $row = new Match( $database );
		$row->save_array($_POST['match_id'],$_POST,false,$project->id);
        $row->bind( $_POST );
	    $row->checkin();
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Match( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'publish':
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&round=$round");
      break;
      
      case 'unpublish';
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&round=$round");
      break;
      
      case 'remove':
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $row = new Match( $database );
        $row->removeMatch($cid);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&round=$round");
      break;
      
      
      default:
        
        $round = (intval(mosGetParam($_REQUEST,'round', 0)) > 0) ? $_REQUEST["round"] : $project->current_round;
        
        $rounds = array();
// added round_date_first, round_date_last to query and removed round_date
        $query="SELECT id, matchcode, name, round_date_first, round_date_last FROM #__joomleague_rounds WHERE project_id = $project->id order by matchcode,round_date_first";
        $database->setQuery($query);
        $results = $database->loadObjectList();
        $temp = array();
        foreach($results as $result){
          if(!in_array($result->name, $temp))
            $rounds[] = mosHTML::makeOption($result->matchcode, sprintf("%s", $result->name)); 
          array_push($temp, $result->name);
        }

        $round_list = mosHTML::selectList( $rounds, 'round', 'class="inputbox" 
                      onChange="javascript:document.roundForm.submit();" size="1"','value', 'text', $round );
        unset($rounds);
        $query= sprintf("SELECT m.*, t1.name AS team1, t2.name AS team2,  u.name AS editor
                                FROM #__joomleague_matches AS m
                           LEFT JOIN #__users AS u ON u.id = m.checked_out
                           LEFT JOIN #__joomleague_teams AS t1 ON t1.id = m.matchpart1
                           LEFT JOIN #__joomleague_teams AS t2 ON t2.id = m.matchpart2
                           LEFT JOIN #__joomleague_rounds AS r ON r.id = m.round_id
                 WHERE m.project_id = %s AND r.matchcode = %s",$project->id, $round);
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_matches.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    } 
    
  break;
  
  case 'matchevents':
    
    switch($task){
      
      case 'new':
      case 'edit':
        
        $row = new MatchEvent( $database );
        $row->load( $cid[0]);
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $match = new Match( $database );
        $match->load( $_SESSION["joomleague_match"] );
        
        #we need Players of matchpart1 and matchpart2
        
        $query = sprintf("SELECT pl.id, pl.firstname,pl.lastname,
                          pos.name AS positionname, t.name AS teamname
                          FROM #__joomleague_players pl
                          LEFT JOIN #__joomleague_playertool pt
                          ON pl.id = pt.player_id
                          LEFT JOIN #__joomleague_positions AS pos
                          ON pos.id = pt.position_id
                          LEFT JOIN #__joomleague_teams AS t
                          ON t.id = pt.team_id
                          WHERE team_id in (%s,%s) AND isStaff=0 AND
                          pt.project_id = %s ORDER BY t.id, pos.ordering",$match->matchpart1,$match->matchpart2,$project->id);
        
        $database->setQuery($query);
        if (!$results = $database->loadObjectList()) {
          // echo $database->getErrorMsg();
          // echo $database->getQuery();
        }
        $options[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYER );
        foreach($results as $result){
            $options[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s - %s)", $result->lastname, $result->firstname, $result->teamname, $result->positionname)); 
        }

        $playerlist = mosHTML::selectList( $options, 'player_id', 'class="inputbox" size="1"','value', 'text', $row->player_id );
        unset($options);
        
        $options[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EVENT );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_eventtypes" );
        $options = array_merge( $options, $database->loadObjectList() );

        $eventtypelist = mosHTML::selectList( $options, 'event_type_id', 'class="inputbox" size="1"','value', 'text', $row->event_type_id );
        unset( $options );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_matchevents.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
      
      case 'save':
        $matchevent = new Matchevent( $database );
        //if (!$_POST['event_sum']) $_POST['event_sum']=1;
        $matchevent->save($_POST, "");
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Matchevent( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Matchevent( $database );
        $row->delete_array($cid, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      default:
        $match = new Match( $database );
        $match->load( $_SESSION["joomleague_match"] );
        
        $query = sprintf("SELECT e.*, p.lastname as lastname, p.firstname as firstname, et.name as event_type_name,
        u.name as checkoutuser, a.joomleague_admin, a.joomleague_editor
                            FROM #__joomleague_match_events e
                       LEFT JOIN #__joomleague_players p on p.id = e.player_id
                       LEFT JOIN #__joomleague_eventtypes et on et.id = e.event_type_id
                       LEFT JOIN #__joomleague a on e.project_id = a.id
                       LEFT JOIN #__users u on e.checked_out = u.id
                           WHERE match_id = %s 
                        ORDER BY e.event_time", $_SESSION["joomleague_match"]);
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_matchevents.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
    }
  break;
  
  case 'rounds':
    
    switch($task){
      case 'copyfrom':
	      $source_round_id=intval(mosGetParam($_REQUEST,'copyfrom',0));
	      $dest_round_id=intval(mosGetParam($_REQUEST,'id',0));
	      $start_match_number=intval(mosGetParam($_REQUEST,'start_match_number',0));
	      $create_new=intval(mosGetParam($_REQUEST,'create_new',0));
	      $mirror=intval(mosGetParam($_REQUEST,'mirror',0));
	      $project_id=intval(mosGetParam($_REQUEST,'project_id',0));
	      $default_match_date=mosGetParam($_REQUEST,'date','');
	      $default_match_time=mosGetParam($_REQUEST,'time','');
	      $query="SELECT match_number, matchpart1, matchpart2 FROM #__joomleague_matches
	      		WHERE project_id = $project_id AND round_id = $source_round_id
	      		ORDER BY match_number, match_date";
	      $database->setQuery($query);
	      $source_matches = $database->loadObjectList();
	      if ($create_new == 1) {
	        for ($x=0;$x<count($source_matches); $x++) {
	          $source_match = $source_matches[$x];
	          $match = new Match($database);
	          if ($mirror == 1) {
	            $match->set('matchpart1', $source_match->matchpart2);
	            $match->set('matchpart2', $source_match->matchpart1);
	          }
	          else {
	            $match->set('matchpart1', $source_match->matchpart1);
	            $match->set('matchpart2', $source_match->matchpart2);
	          }
	          if ($start_match_number > 0) {
	            $match->set('match_number', $start_match_number);
	            $start_match_number++;
	          }
	          $match->set('match_date', $default_match_date.' '.$default_match_time);
	          $match->set('round_id', $dest_round_id);
	          $match->set('project_id', $project_id);
	          $match->save(array(),false);
	        }
	      }
	      else {
	        $query="SELECT match_id, matchpart1, matchpart2 FROM #__joomleague_matches
	      		WHERE project_id = $project_id AND round_id = $dest_round_id
	      		ORDER BY match_number, match_date";
	        $database->setQuery($query);
	        $dest_matches = $database->loadObjectList();
	      	  for ($x=0;$x<count($source_matches);$x++) {
	      		  $source_match = $source_matches[$x];
	      		  $dest_match = $dest_matches[$x];
	      		  $match = new Match($database);
	      		  $match->load($dest_match->match_id);
	            if ($mirror == 1) {
	              $match->set('matchpart1', $source_match->matchpart2);
	              $match->set('matchpart2', $source_match->matchpart1);
	            }
	            else {
	              $match->set('matchpart1', $source_match->matchpart1);
	              $match->set('matchpart2', $source_match->matchpart2);
	            }
	            if ($start_match_number > 0) {
	              $match->set('match_number', $start_match_number);
	              $start_match_number++;
	            }
	            $match->set('match_date', $default_match_date.' '.$default_match_time);
	            $match->set('round_id', $dest_round_id);
	            $match->set('project_id', $project_id);
	            $match->save(array(),false);
	      	  }
	      }
				mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=".$dest_round_id);
	      break;
      case 'new':
      case 'edit':
        $row = new Round( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_rounds.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
        break;
      
      case 'return':
        $round = new Round( $database );
        foreach ($cid as $rid) {
          $round->load($rid);
          $games = $round->getMatches();
          $round->set('name', $round->name.' return');
          $round->set('matchcode', $round->matchcode+1000);
          $round->set('id', NULL); //to trigger creation
          $round->store();
          
          $return = new Match( $database );
          $first_leg = new Match( $database );
          foreach ($games as $game) {
            $first_leg->load( $game );
            $return->set( 'matchpart1', $first_leg->matchpart2 );
            $return->set( 'matchpart2', $first_leg->matchpart1 );
            $return->set( 'project_id', $first_leg->project_id );
            $return->set( 'round_id', $round->id );
            $return->set( 'match_id', NULL );
            //print_r($return);
            $return->store();
          }
        }
        unset ($round,$games, $return,$first_leg);
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
        break;
      
      case 'save':
        $row = new Round( $database );
        $row->save($_POST, "project_id = $project->id");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'cancel':
        $row = new Match( $database );
        foreach($cid as $cids) {
          $row->checkin( $cids );
        }
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=".$_POST['id']);
      break;
      
      case 'savematches':
        $row = new Match( $database );
				foreach($cid as $cids) {
					$row->save_array($cids,$_POST,true,$project->id);
			    $row->checkin( $cids );
				}
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=".$_POST['id']);
      break;
      
      case 'publishmatches':
        $row = new Match( $database );
        $round = $row->publish_array($cid, $_POST, 1, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=$round");
      break;
        
      case 'deletematches':
        $row = new Match( $database );
        $round = $row->removeMatch($cid);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=$_POST[round]");
      break;
      
      case 'unpublishmatches':
        $row = new Match( $database );
        $round = $row->publish_array($cid, $_POST, 0, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=$round");
      break;
      
      case 'setmatchesnull':
        $row = new Match( $database);
        $round = $row->setNull($cid, $_POST, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act&task=tab2&round=$round");
      break;
      
      case 'remove':
        $round = new Round( $database );
        if (!$round->deleteRound($cid)) {
          mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act", "Please delete Matches first");
				} else {
		          mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
				}
      break;
      
      case 'matrix':
        $config = $project->getTemplateConfig("show_results.tpl");
        $overall_config = $project->getTemplateConfig("overall.tpl");
        if(isset($_POST['func']) && mosGetParam($_POST,'func','') == 'savematch'){
        	$countmatches=intval(mosGetParam($_POST,'add_match_count',1));
          for ($x=0;$x < $countmatches;$x++) {
	          $match = new Match( $database );
	          $match->bind( $_POST );
	          $match->save(array(),false);
	        }
        } 
        
        $round = intval(mosGetParam($_REQUEST,'round', 0)); 
        if($round == 0) $round = $cid[0];  
      // *** important!!! *** $selected_round is used the whole process of creating new and editing matches
        $selected_round = new Round( $database );
        $selected_round->load( $round );
   
        $myrounds = $project->getRoundNames();
        foreach($myrounds as $result){
            $datum = mosFormatDate($result->round_date_first.' 00:00:00', '%d.%m.%Y', $project->serveroffset);
            if ($result->round_date_last!='0000-00-00') $datum .= '-'.mosFormatDate($result->round_date_last.' 00:00:00', '%d.%m.%Y', $project->serveroffset);
            $rounds[] = mosHTML::makeOption($result->id, sprintf("%s  (%s)", $result->name,$datum)); 
        }
        
        $round_list = mosHTML::selectList( $rounds, 'round', 'class="inputbox" 
                      onChange="javascript:document.roundForm.submit();" size="1"','value', 'text', $selected_round->id );
        $copy_round_list = mosHTML::selectList( $rounds, 'copyfrom', 'class="inputbox" size="1"','value', 'text', $selected_round->id );
        unset($rounds);
        $matches = $project->getResults($selected_round->matchcode, "ASC", 1);
        $match_list = array();
        $mdd[] = mosHTML::makeOption( 0, _JL_ADMIN_EDIT_LIST_MATCHES_TITLE );
      
	      foreach($matches as $v){
					$match = new Match($database);
					$match->load($v->match_id);
					$home = new JL_Team($database);
					$home->load($match->matchpart1);
					$away = new JL_Team($database);
					$away->load($match->matchpart2);
					if (!$match->checked_out || $match->checked_out == $my->id || strtolower($my->usertype) == 'super administrator') {
	          $match_list[] = $match->matchpart1.'_'.$match->matchpart2;
	          $mdd[] = mosHTML::makeOption( "index3.php?option=com_joomleague&act=editEvents&p=".$project->id."&mid="
	             .$match->match_id."&no_html=1", $home->name." - ".$away->name );
	        }
	      }
    	   
      	/* if referee is one other team */
        if ($project->teams_as_referees)
        {
          $query = "SELECT id, name, short_name FROM #__joomleague_teams ORDER BY name";        	
        	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s", $result->name)); 
          }
        }
        else
        {
          $query = "SELECT id, firstname, lastname FROM #__joomleague_referees ORDER BY lastname";
       	
        	$database->setQuery($query);
          $results = $database->loadObjectList();
          $ref[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_REFEREE );
          foreach($results as $result){
          	$ref[] = mosHTML::makeOption($result->id, sprintf("%s, %s", $result->lastname, $result->firstname)); 
          }
        }
       
        $teams = $project->getTeams();
        $matrix ='';
        if (count($teams) <= 20) {
        $matrix = "<table width=\"100%\" class=\"adminlist2\">";
         
         $k = 0;
         for($rows = 0; $rows <= count($teams); $rows++){
          if($rows == 0) $trow = $teams[0];
          else $trow = $teams[$rows-1];
          
          
          $matrix .= "<tr class=\"row$k\">";
          
            for($cols = 0; $cols <= count($teams); $cols++){
              
              $text = '';
              $checked = '';
              $color = 'white';
              
              if( $cols == 0 ) $tcol = $teams[0]; 
              else $tcol = $teams[$cols-1];
              
              $match = $trow->id.'_'.$tcol->id;
                
              if(in_array($match,$match_list)){
                $checked = 'checked';
                $color = 'teal';
              }
              
              if($rows == 0 && $cols == 0) $text = sprintf("<td align=\"center\"><b>%s</b></td>",$project->name);
              else if($rows == 0) $text = sprintf("<td width=\"200\" align=\"center\" title=\"%s\">%s</td>",$tcol->name,$tcol->short_name); //picture columns
              else if($cols == 0) $text = sprintf("<td align=\"left\" nowrap>%s</td>",$trow->name); // named rows
              else if($rows == $cols) $text = "<td align=\"center\"><input type=\"radio\" DISABLED></td>"; //impossible matches
              else{
                $onClick = sprintf("onClick=\"javascript:SaveMatch('%s','%s','%s');\"",$trow->id,$tcol->id,$selected_round->id);
                $text = sprintf("<td align=\"center\" title=\"%s - %s\" bgcolor=\"%s\"><input type=\"radio\" name=\"match_%s\" %s %s></td>\n",$trow->name,$tcol->name,$color,$trow->id.$tcol->id, $onClick, $checked);
              }
              $matrix .= $text;
            }
          $k = 1 - $k;
          
         }
          
         $matrix .= "</table>";
        }
         $view = JL_ADMIN_TEMPLATE_PATH.'/edit_matrix_rounds.tpl.php';    
         require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
      
      break;
      
      default:        
//changed second ordering to round_date_first Gucky 2007/05/25    
        $database->setQuery( "SELECT r.*, u.name AS editor
                                FROM #__joomleague_rounds AS r
                           LEFT JOIN #__users AS u ON u.id = r.checked_out
                               WHERE r.project_id = ".$project->id."
                            ORDER BY r.matchcode, r.round_date_first");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_rounds.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
    }
  break;
  case 'postool':
    require JL_ADMIN_PATH.'/lib/inc.positionstool.php';
    switch($task){
      case 'saveAll':
        if(isset($_POST["positions"])) {
          jl_save_positions($_POST["positions"], $project->id);
        }
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
        break;
      case 'assign':
      default:
        jl_assign_positions ();
        break;
    }
  break;
  case 'teamtool':
    
    switch($task){
      
      case 'saveAll':
        $msg = $project->assignTeams($_POST);
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act", $msg );
      break;
      
      case 'saveOne':
      case 'apply':
        $row = new TeamTool( $database );
        $row->save($_POST, "");
        if ($task=='saveOne') mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
        else mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act&task=edit&cid[0]=$row->id" );
      break;
      
      case 'cancel':
        $row = new TeamTool( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      
      
      case 'edit':
        
        $row = new TeamTool( $database );
        $row->load($cid[0]);
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $t = new JL_Team( $database);
        $t->load($row->team_id);
        
        $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_USER );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__users " );
        $users = array_merge( $users, $database->loadObjectList() );

        $user_list = mosHTML::selectList( $users, 'admin', 'class="inputbox" size="1"','value', 'text', $row->admin );
        unset( $users );
        
        $divisions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_DIVISION );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_divisions WHERE project_id=$project->id" );
                                
        $divisions = array_merge( $divisions, $database->loadObjectList() );
        $divisionlist = mosHTML::selectList( $divisions, 'division_id', 'class="inputbox" size="1"','value', 'text', $row->division_id );
        unset( $divisions );
        
        $playgrounds[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYGROUND );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_playgrounds ORDER BY name");
        $playgrounds = array_merge( $playgrounds, $database->loadObjectList() );
        $playgroundslist = mosHTML::selectList( $playgrounds, 'standard_playground', 'class="inputbox" size="1"','value', 'text', $row->standard_playground );
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_teamtool.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';    
        
      break;
      
      case 'copy':
/*
        $row = new JL_Team( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id) {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
*/

        $projects[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PROJECT );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague WHERE id <> $project->id");
        $projects = array_merge( $projects, $database->loadObjectList() );

        $clist = mosHTML::selectList( $projects, 'project_id', 'class="inputbox" size="1"','value', 'text', 0 );
        $cids = implode(",",$cid);
        $view = JL_ADMIN_TEMPLATE_PATH.'/copy_form_teams.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';            

      break;

	  case 'copysave':
		if (isset($_POST["old_id"])) $old_id = $_POST["old_id"];
		if (isset($_POST["cids"])) $cids = $_POST["cids"];

        $database->setQuery( 'SELECT team_id, admin, info, checked_out, checked_out_time, picture, description, standard_playground FROM #__joomleague_team_joomleague WHERE project_id='.$old_id.' AND id IN ('.$cids.')');
        $results = $database->loadObjectList();
		
		foreach($results as $result) {
			$names = 'project_id, team_id, admin, info, checked_out, checked_out_time';
			$values = sprintf("'%s','%s','%s','%s','%s','%s'",$_POST['project_id'],$result->team_id,$result->admin,$result->info,$result->checked_out,$result->checked_out_time, $result->standard_playground);
			if (isset($result->picture)) {
				$names .= ', picture';
				$values .= sprintf(",'%s'",$result->picture);
			}
			if (isset($result->description)) {
				$names .= ', description';
				$values .= sprintf(",'%s'",$result->description);
			}
			$names .= ', standard_playground';
			if (isset($result->standard_playground)) {
				$values .= sprintf(",'%s'",$result->description);
			} else $values .= ', NULL';

			$query = "INSERT INTO #__joomleague_team_joomleague ($names) VALUES ($values)";
			$database->setQuery($query);
			$database->query($query);

	        $database->setQuery("SELECT * FROM #__joomleague_playertool WHERE project_id=$old_id AND team_id = $result->team_id");
    	    $results = $database->loadObjectList();

			foreach($results as $result) {
				$names = 'player_id,team_id,project_id,position_number,position_id,weight,height,injury,injury_date,injury_end,injury_detail,suspension,suspension_date,suspension_end,suspension_detail,picture,description,published,checked_out,checked_out_time';
				$values = sprintf("'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",$result->player_id,$result->team_id,$_POST['project_id'],$result->position_number,$result->position_id,$result->weight,$result->height,$result->injury,$result->injury_date,$result->injury_end,$result->injury_detail,$result->suspension,$result->suspension_date,$result->suspension_end,$result->suspension_detail,$result->picture,$result->description,$result->published,$result->checked_out,$result->checked_out_time);
			
				$query = "INSERT INTO #__joomleague_playertool ($names) VALUES ($values)";
				$database->setQuery($query);
				$database->query($query);
			}
		}

		if ($_POST['chance_project']==1) { 
		  $_SESSION["joomleague"] = $_POST['project_id'];
          session_unregister("joomleague_team");
          session_unregister("joomleague_match");
		  mosRedirect(JL_ADMIN_COMPONENT_LINK.'&act=teamtool');
		}
        else {
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
		} 

	  break;
      
      case 'assign':
        
        //teams already assigned to a project
        $teams = $project->getTeams();
        
        //we dont need these teams in the first list
        $ids = array();
        foreach($teams as $team){
          $ids[] = $team->id;
        }
        
        $v = (count($ids) > 0)? sprintf("WHERE id not in (%s)", implode(",",$ids)) : "";
        $database->setQuery( "SELECT id, name, description 
                                FROM #__joomleague_teams 
                                  $v 
                               ORDER BY name");
        $results = $database->loadObjectList();
        
        $teams1 = array();
        foreach($results as $result){
            $teams1[] = mosHTML::makeOption($result->id, sprintf("%s (%s)", $result->name,$result->description)); 
        }

        //$tlist1 = mosHTML::selectList( $teams1, 'list1', 'class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list1,document.adminForm.list2)" style="width:350px;"','value', 'text','');
        
        $teams2 = array();
        
        
        if(count($teams) > 0){
          foreach($teams as $team){
            $teams2[] = mosHTML::makeOption($team->id, sprintf("%s (%s)",$team->name,$team->description));
          }
        }
        
        //$tlist2 = mosHTML::selectList( $teams2, 'list2','class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list2,document.adminForm.list1)" style="width:350px"','value','text','');        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_assign_teams.tpl.php';    
        $path=_JOOMLA_JL_LIVE_SITE;
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
         
      break;
      case 'saveShort': //save start_points and division_id if present
	      foreach ( $cid = mosGetParam($_REQUEST, 'cid', array(0)) as $ttid ) {
	      	$update = array ();
	      	if ( $divId = mosGetParam($_REQUEST, 'division_id'.$ttid, 0) )
	      	   $update['division_id'] = $divId;
	      	$update['start_points'] = mosGetParam($_REQUEST, 'start_points'.$ttid, 0);
	      	$team = new Teamtool($database);
	      	if ( $team->load($ttid) ){
	      		$team->bind($update);
	      		$team->store();    	 
	      	}
	      }
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=teamtool");
	      break;
      
      default:
        #list teams2project
        
        $ordering = '';
        if ($project->project_type == 'DIVISIONS_LEAGUE') {
          $divisions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_DIVISION );
          $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_divisions WHERE project_id=$project->id" );
                                
          $divisions = array_merge( $divisions, $database->loadObjectList() );
          $ordering='tl.division_id, d.ordering, name';
        }
        $rows = $project->getTeams($ordering);
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_teamtool.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
    }
  break;

  case 'divisions':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new LeagueDivision( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        //get divisions already in project for parents list
        //support only 2 sublevel, so parent must not have parents themselves
        $query = "SELECT id, name FROM #__joomleague_divisions
        			        WHERE project_id=$project->id AND parent_id=0
                      ORDER BY name";
        $database->setQuery( $query );
        $results = $database->loadObjectList();
        $divisionList[] = mosHTML::makeOption(0, _JL_ADMIN_EDIT_FORM_DIVISIONS_SELECT_PARENT);
        foreach ($results as $result) {
          $divisionList[] = mosHTML::makeOption($result->id, $result->name);
        }

        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_divisions
			                                 WHERE project_id=$project->id
                                       ORDER BY ordering");
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );

        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_divisions.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new LeagueDivision( $database );
	      $row->save($_POST, "");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new LeagueDivision( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new LeagueDivision( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;   
      
      case 'orderup':
        $row = new LeagueDivision( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "project_id=$project->id" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'orderdown':
        $row = new LeagueDivision( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "project_id=$project->id" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;      
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_divisions AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, p.name AS parent_name, u.name AS editor
                                FROM #__joomleague_divisions AS a
                                LEFT JOIN #__users AS u ON u.id = a.checked_out
                                LEFT JOIN #__joomleague_divisions AS p ON p.id = a.parent_id
                            WHERE a.project_id=$project->id
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();  
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_divisions.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
  
    break;
  
  case 'projects':
    
    switch($task){
      
      case 'copy':
      case 'new':
      case 'edit':
        
        $proj = new JoomLeague($database);
        if ($proj->load( $cid[0] ))
          $doTips_config=$proj->getTemplateConfig("do_tips.tpl");
        else {//project doesn't exists...
          $doTips_config = array();
        } 

        if ($proj->checked_out && $proj->checked_out <> $my->id) {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }

        $old_id = '';
        if ($task=='copy') {
    			$old_id = $cid[0];
    			$proj->id='';
    			$proj->current_round='1';
    		}

        if ($cid[0]) {
          $proj->checkout( $my->id );
        }
        
        // leagues dropdown
        $leagues[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_LEAGUE );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_leagues 
                            ORDER BY ordering" );
        $leagues = array_merge( $leagues, $database->loadObjectList() );

        $league_list = mosHTML::selectList( $leagues, 'league_id', 'class="inputbox" size="1"','value', 'text', $proj->league_id );
        unset( $leagues );  
        
        // seasons dropdown
        $seasons[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_SEASON );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__joomleague_seasons 
                            ORDER BY ordering" );
        $seasons = array_merge( $seasons, $database->loadObjectList() );

        $season_list = mosHTML::selectList( $seasons, 'season_id', 'class="inputbox" size="1"','value', 'text', $proj->season_id );
        unset( $seasons );
        
        // projects list for master template
        /// define onclick for else we get warnings - please turn all on error reporting while developing!!!
        $onclick='';
        $master_tpl[] = mosHTML::makeOption( '0', _JL_ADMIN_EDIT_FORM_PROJECTS_OWN_TEMPLATE );
        $query = "SELECT name as text, id as value FROM #__joomleague WHERE master_template = 0";
        if (intval($proj->id)) { $query .= " AND id <> $proj->id"; }
        $query .= " ORDER BY name";
        if (!$database->setQuery( $query )) { echo $database->getErrorMsg(); } 
        $master_tpl = array_merge( $master_tpl, $database->loadObjectList() );
        if ($task == 'new') {
          $onclick = "onclick='if(this.value == 0) {document.forms[0].copyTemplate.disabled=false;}
                                else {document.forms[0].copyTemplate.disabled=true;}'";
        }
        $templates_list = mosHTML::selectList( $master_tpl, 'master_template', 'class="inputbox" size="1" '.$onclick,'value', 'text', $proj->master_template );
        unset( $master_tpl );

        // users list for project admin
        $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_ADMIN );
        $database->setQuery( "SELECT id AS value, CONCAT(name, ' (', usertype, ')') AS text 
                               FROM #__users 
                               WHERE usertype = ('Super Administrator') OR usertype = ('Administrator') OR usertype = ('Manager') 
                               ORDER BY gid DESC" );
        $users = array_merge( $users, $database->loadObjectList() );

        $user_list = mosHTML::selectList( $users, 'joomleague_admin', 'class="inputbox" size="1"','value', 'text', $proj->joomleague_admin );
        unset( $users );
        
        // users list for project editor
        $editors[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_EDITOR );
        $database->setQuery( "SELECT id AS value, CONCAT(name, ' (', usertype, ')') AS text 
                                FROM #__users ORDER BY gid DESC" );
        $editors = array_merge( $editors, $database->loadObjectList() );

        $editor_list = mosHTML::selectList( $editors, 'joomleague_editor', 'class="inputbox" size="1"', 'value', 'text', $proj->joomleague_editor );
        unset( $editors );

        // list of fireboards categories
        if ( in_array( $mosConfig_dbprefix.'fb_categories', $database->getTableList() ) ) 
        {
	        $fireboards[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_FIREBOARD );
	        $database->setQuery( "SELECT id AS value, name AS text 
	                                FROM #__fb_categories WHERE parent > 0
	                            ORDER BY ordering" );
	        $fireboards = array_merge( $fireboards, $database->loadObjectList() );
	
	        $fireboard_list = mosHTML::selectList( $fireboards, 'sb_catid', 'class="inputbox" size="1"','value', 'text', $proj->sb_catid );
	        unset( $fireboards );
        }
        else $fireboard_list = '';                  
        
        // teams list for fav teams selection
        if($cid[0] > 0){

          $query = "SELECT t.id AS value, t.name AS text
                      FROM #__joomleague_teams t, #__joomleague_team_joomleague tp
                     WHERE t.id = tp.team_id AND tp.project_id = ".$cid[0];
            
          $database->setQuery( $query );
          $teams = $database->loadObjectList();
        }
        else {
          $proj->init(); // does it serve any purpose ??
        }
  
        $tempfavs=explode(",", $proj->fav_team);
  	    if ( count($tempfavs) ) {
       	  foreach($tempfavs AS $tempfav) { $selected[]->value = $tempfav;}
  	    }
        $team_list = mosHTML::selectList( $teams, 'fav_team[]', 'class="inputbox" size="20" multiple="true"','value', 'text', $selected );
        unset( $teams );
        
        // list of folders in frontend (for extensions/design template)
        $folder = array();
        $handle=opendir( JL_FRONTEND_PATH.'/frontend' ); 
        while ($file = readdir ($handle)) {
          if( $file != "index.html" && $file != "." && $file != ".."){
            $folder[] = mosHTML::makeOption( $file, $file );
          }
        }
        closedir($handle); 
        $folder_list = mosHTML::selectList( $folder, 'template', 'class="inputbox" size="1"','value', 'text', $proj->template );
        unset( $folder );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_projects.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
   
      break;
      
      case 'save':
        $proj = new JoomLeague( $database );
        $temp=$_POST;
        $isnew = ( intval(mosGetParam($_POST, 'id', 0) ) == 0 ) ? true : false;
        
        // format fav_team
        if ( count( $temp["fav_team"] ) > 0 ) {
          $temp["fav_team"] = implode( ",", $_POST['fav_team'] );
        }
        else {
          $temp["fav_team"]="";
        }
        $proj->save($temp, false);
        
        //create new league ?
        if ( $temp['newLeagueCheck'] ) {
          $nl = new League( $database );
          $nl->set( 'name', $_POST['leagueNew'] );
          $nl->store();
          $proj->set( 'league_id', $nl->id );
        }
        
        //create new season ?
        if ( $temp['newSeasonCheck'] ) {
          $sl = new Season( $database );
          $sl->set( 'name', $_POST['seasonNew'] );
          $sl->store();
          $proj->set( 'season_id', $sl->id );
        }
        // store project
        $proj->store();
        // print_r($proj);
        
        //import xml templates settings
        if ( isset($_POST['copyTemplate']) && $_POST['copyTemplate'] ) {
          $template = new TemplateConfig($database);
          
          $query = "SELECT id FROM #__joomleague_template_config WHERE project_id=".$_POST['copyTemplate'];
    		  $database->setQuery($query);
    		  $templates = $database->loadObjectList();
    		  foreach ($templates AS $tp) {
            $template->load($tp->id);
            $template->set( 'project_id', $proj->id );
            $template->set( 'id', NULL );
            $template->store();
          }
        }
        else if ( $isnew && $_POST['master_template'] == 0 )
        {
        	// init the templates settings
        	checkTemplateList( $proj ); 
        }
        
        mosRedirect( JL_ADMIN_COMPONENT_LINK );
      break;
      
      case 'copysave':
      	copyProject($_POST);  
        mosRedirect( JL_ADMIN_COMPONENT_LINK, $project_id );
      break;
            
      case 'apply':
        $row = new JoomLeague( $database );
        $temp=$_POST;
        if (count($temp["fav_team"])>0) $temp["fav_team"]=implode(",", $_POST['fav_team']);
        else $temp["fav_team"]="";
        $row->save($temp, false);
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=projects&task=edit&cid[0]=$id" );
        
      break;       
      
      case 'remove':
        $row = new JoomLeague( $database );
		    foreach($cid as $cids) {
	        $row->delete($cids);
	        echo "<pre>";
    			$query=sprintf("DELETE FROM #__joomleague_rounds WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "<br>$entrys ZUGEH&Ouml;RIGE SPIELTAGE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_rounds\n
    						FLUSH TABLE #__joomleague_rounds";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_matches WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE SPIELE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_matches\n
    						FLUSH TABLE #__joomleague_matches";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_match_events WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE EREIGNISSE ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_match_events\n
    						FLUSH TABLE #__joomleague_match_events";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_playertool WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE SPIELER ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_playertool\n
    						FLUSH TABLE #__joomleague_playertool";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_team_joomleague WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TEAMS ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_team_joomleague\n
    						FLUSH TABLE #__joomleague_team_joomleague";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_template_config WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TEMPLATEKONFIGURATIONEN ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_template_config\n
    						FLUSH TABLE #__joomleague_template_config";
    				$database->query( $database->setQuery($query));
    			}
			
    			$query=sprintf("DELETE FROM #__joomleague_tip_members WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TIPPSPIELMITGLIEDER ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_tip_members\n
    						FLUSH TABLE #__joomleague_tip_members";
    				$database->query( $database->setQuery($query));
    			}
    			
    			$query=sprintf("DELETE FROM #__joomleague_tip_results WHERE project_id = %s",$cids);
    			$database->query( $database->setQuery($query));
    			$entrys=$database->getAffectedRows();
    			if ($entrys>0) {
    				echo "$entrys ZUGEH&Ouml;RIGE TIPPS ZUM PROJEKT #".$cids." WURDEN GEL&Ouml;SCHT<br>";
    				$query="OPTIMIZE TABLE #__joomleague_tip_results\n
    						FLUSH TABLE #__joomleague_tip_results";
    				$database->query( $database->setQuery($query));
    			}
    			
    			if ($_SESSION["joomleague"]== $cids) {
            session_unregister("joomleague");
            session_unregister("joomleague_team");
            session_unregister("joomleague_match");
          }
		    }
        echo "<br /><br /><b>You will be redirected to the JoomLeague Administration Homepage in 5 seconds!<b>";?>
        <meta http-equiv="refresh" content="5; url=<?php echo JL_ADMIN_COMPONENT_LINK;?>"/>
        <?php				
              //mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new JoomLeague( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK );
      break;
      
      case 'publish':
        $row = new JoomLeague( $database );
        $round = $row->publish_array($cid, 1, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'unpublish';
        $row = new JoomLeague( $database );
        $round = $row->publish_array($cid, 0, $my->id);
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $seasonfilter = $mainframe->getUserStateFromRequest( "view{$option}{$act}season", 'season', 0 );

        $where = array();
        if ($seasonfilter) {
            $where[] = "a.season_id = $seasonfilter";
        }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague AS a" 
                            . ( count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "") );
        $total = $database->loadResult();

        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*,l.name AS league, s.name AS season, uu.name AS admin, u.name AS editor, uuu.name AS checkoutuser
                                FROM #__joomleague AS a
                           LEFT JOIN #__joomleague_leagues AS l ON l.id = a.league_id
                           LEFT JOIN #__joomleague_seasons AS s ON s.id = a.season_id
                           LEFT JOIN #__users AS uu ON uu.id = a.joomleague_admin
                           LEFT JOIN #__users AS u ON u.id = a.joomleague_editor
                           LEFT JOIN #__users AS uuu ON uuu.id = a.checked_out"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.name, l.name, s.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");

        $rows = $database->loadObjectList();        
        
        $seasons[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_SEASON );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_seasons ORDER BY name");
        $seasons = array_merge( $seasons, $database->loadObjectList() );

        $seasonslist = mosHTML::selectList( $seasons, 'season', 'class="inputbox" size="1" onchange="document.adminForm.submit();"','value', 'text', $seasonfilter );
        unset($seasons);
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_projects.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';         

      break;
    }
  
  break;
  
  case 'leagues':  
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new League( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_leagues
                                    ORDER BY ordering");
    
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        $selectedvalue=$row->country;
        $countrycode=explode("_", _JL_LOCALE);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->country)) $selectedvalue=$result->countries_id;
        		$value=$result->countries_localname;
        	}
        	else {
        		if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
        		else $value=$result->countries_name;
        	}
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        if (is_null($row->country)) $clist.="<b>"._JL_ADMIN_NOT_USED."</b>";
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_leagues.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
      
      case 'save':
        $row = new League( $database );
        $row->save($_POST, "");
        $row->updateOrder( );
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new League( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new League( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'orderup':
        $row = new League( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'orderdown':
        $row = new League( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_leagues AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_leagues AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_leagues.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
    }
    
  break;
    
  case 'seasons':
   
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Season( $database );
        $row->load( $cid[0] );
        
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_seasons
			                              ORDER BY ordering");

        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_seasons.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
      
      case 'save':
         $row = new Season( $database );
	     $row->save($_POST, "");
         $row->updateOrder( );
	     mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'remove':
        $row = new Season( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Season( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'orderup':
        $row = new Season( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'orderdown':
        $row = new Season( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_seasons AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_seasons AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_seasons.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';
        
      break;
    }
  
  break;
  
  case 'positions':
 
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new Position( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $order = mosGetOrderingList( "SELECT ordering AS value, name AS text
			                                  FROM #__joomleague_positions
                                    ORDER BY ordering");
    
        $list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', intval( $row->ordering ) );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_positions.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
      
      case 'save':
        $row = new Position( $database );
        $row->save($_POST, "");
        $row->checkin();
        $row->updateOrder();
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'cancel':
        $row = new Position( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Position( $database );
        $row->bind( $_POST );
        $res = true;
        for ($x=0;$x<count($cid);$x++)
        {
        	$res = $res && $row->delete($cid[$x]);
        }
        if ($res) {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
        }
        else {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act", $row->getError());
        }
      break;            
      
      case 'orderup':
        $row = new Position( $database );
	      $row->load( $cid[0] );
	      $row->move( -1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'orderdown':
        $row = new Position( $database );
	      $row->load( $cid[0] );
	      $row->move( 1, "" );

	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_positions AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_positions AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                            ORDER BY a.ordering
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_positions.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
    }
    
  break;
  
  case 'eventtypes':
    
    switch($task){
      
      case 'new':
      case 'edit':

        
        $row = new Eventtype( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        // select list of images for events icons
			  $images[] = mosHTML::makeOption( '', _JL_ADMIN_SELECT_PICTURE );
			  if ( is_dir(_JOOMLA_JL_PATH . '/images/joomleague/event_icons/') && $dp = opendir( _JOOMLA_JL_PATH . '/images/joomleague/event_icons/' ) )
			  {
			    $list = array();
			    while ( ( $file = readdir( $dp ) ) !== false )
			    {
			      if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $file ) ) {
			        $list[] = $file;
			      }
			    }
			    if ( count($list) ) 
			    {
			      sort( $list );
			      foreach ($list as $l) {
			        $images[] = mosHTML::makeOption( $l, $l );
			      }
			    }
			    closedir($dp);
			  }
			  
			  $icons_selector = mosHTML::selectList( $images, 'icon_sel', 
                        'class="inputbox" size="1" onchange="document.getElementById(\'icon\').value = this.value; updateIcon();"',
                        'value', 'text', $row->icon );
        unset($images);
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_eventtypes.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
      
      case 'save':
        $row = new Eventtype( $database );
        $row->save($_POST, "");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'cancel':
        $row = new Eventtype( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Eventtype( $database );
        $row->bind( $_POST );
        $res = true;
        for ($x=0;$x<count($cid);$x++)
        {
        	$res = $res && $row->delete($cid[$x]);
        }
        if ($res) {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
        }
        else {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act", $row->getError());
        }
      break;
      
         
      
      default:
              
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );   
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_eventtypes AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );                   
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_eventtypes AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                           LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        

        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_eventtypes.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
    }
    
  break;
  
  case 'events':
   
    switch($task){
      
      case 'new':
      case 'edit':
      
        $row = new MatchEvent( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect(JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_events.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';  
        
      break;
      
      case 'save':
        $row = new MatchEvent( $database );
        $row->save($_POST, "");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'cancel':
        $row = new MatchEvent( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      default:
        $rows = array();
        
        $mid = intval(mosGetParam($_REQUEST, 'match',0));
        if($mid > 0){
          $m = new Match($database);
          $m->load($mid);
        
          $database->setQuery( "SELECT e.*, p.firstname, p.lastname, et.name AS eventtype, u.name AS editor
                                FROM #__joomleague_match_events AS e
                           LEFT JOIN #__joomleague_players AS p on p.id = e.player_id
                           LEFT JOIN #__joomleague_eventtypes AS et on et.id = e.event_type_id
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                               WHERE e.match_id = ".$m->match_id."
                            ORDER BY e.event_time");
          $rows = $database->loadObjectList();        
        }
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_events.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
    
  break;
  
  case 'clubs':
    
    switch($task){
      
      case 'new':
      case 'edit':
        clubs_edit( $cid , $task); 
        break;
      
      case 'save':
      case 'apply':
        $row = new Club( $database );
	      $row->save($_POST, "");
	      if ($_POST['createTeam'])
        {
          //create a new team with same name as club
          $newTeam = new JL_Team( $database );
          $newTeam->set('name', $row->name);
          $newTeam->set('club_id', $row->id);
          $newTeam->set('short_name', 
                            strtoupper( 
                              substr( ereg_replace("[^a-zA-Z]","",$row->name), 0, 3)
                              )
                      );
          $newTeam->store();
        }
        if ($task == 'save') mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
        else mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act&task=edit&cid[]=$row->id"); 
      break;
      
      case 'cancel':
        $row = new Club( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Club( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
        $search = $database->getEscaped( trim( strtolower( $search ) ) );
    
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.name) LIKE '$search%'";
        }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_clubs AS a" 
                            . ( count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "") );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_clubs AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
                
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_clubs.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
    }
  
  break;
  
  case 'teams':
    
    //require_once 'components/com_joomleague/classes/class.Team.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new JL_Team( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        $clubs[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_CLUB );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_clubs ORDER BY name");
        $clubs = array_merge( $clubs, $database->loadObjectList() );

        $clist = mosHTML::selectList( $clubs, 'club_id', 'class="inputbox" size="1"','value', 'text', $row->club_id );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_teams.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;

      case 'save':
        $row = new JL_Team( $database );
	      $row->save($_POST, "");
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new JL_Team( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new JL_Team( $database );
        $row->bind( $_POST );
        $res = true;
        for ($x=0;$x<count($cid);$x++)
        {
        	$res = $res && $row->delete($cid[$x]);
        }
        if ($res) {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
        }
        else {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act", $row->getError());
        }
      break;
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.name) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_teams AS a"
                        . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, c.name AS club, u.name AS editor
                                FROM #__joomleague_teams AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out
                           LEFT JOIN #__joomleague_clubs AS c ON a.club_id = c.id"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.name, club
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_teams.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
  
  break;
  
  case 'playertool':
    
    switch($task){
      case 'saveShort':
	      for ($x=0;$x<count($cid);$x++)
	        {
	        	$query="UPDATE #__joomleague_playertool SET 
	        	position_number = '".$_POST['position_number'.$cid[$x]]."', 
	        	position_id = '".$_POST['position_id'.$cid[$x]]."', 
	        	weight = '".$_POST['weight'.$cid[$x]]."', 
	        	height = '".$_POST['height'.$cid[$x]]."'
	        	WHERE id = ".$cid[$x];
	        	$database->setQuery($query);
	        	$database->query();
	        }
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=playertool");
      case 'edit':
      
        $row = new Playertool( $database );
        $row->load( $cid[0] );
        
        $player = new Player( $database );
        $player->load($row->player_id);
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions WHERE isStaff=0 order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );
        $selectedvalue = 0;
        $position_append = '';
        if ($row->position_id > 0) $selectedvalue = $row->position_id;
        elseif ($player->default_position_id > 0) { $selectedvalue = $player->default_position_id; $position_append = '*';}
        $positionlist = mosHTML::selectList( $positions, 'position_id', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        
        
        $matchdays[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_MATCHDAY );

        $database->setQuery( "SELECT matchcode AS value, name AS text FROM #__joomleague_rounds WHERE project_id = $project->id order by matchcode");
        $matchdays = array_merge( $matchdays, $database->loadObjectList() );

        $injury_date = mosHTML::selectList( $matchdays, 'injury_date', 'class="inputbox" size="1"','value', 'text', $row->injury_date );
        $injury_end = mosHTML::selectList( $matchdays, 'injury_end', 'class="inputbox" size="1"','value', 'text', $row->injury_end );
        $suspension_date = mosHTML::selectList( $matchdays, 'suspension_date', 'class="inputbox" size="1"','value', 'text', $row->suspension_date );
        $suspension_end = mosHTML::selectList( $matchdays, 'suspension_end', 'class="inputbox" size="1"','value', 'text', $row->suspension_end );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_playertool.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';    
        
      break;
      
      case 'saveAll':
        $team->assignPlayers($project, $_POST);
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'saveOne':
        $row = new Playertool( $database );
	      $row->save($_POST, "");
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Playertool( $database );
	      $row->bind( $_POST );
	      $row->checkin();
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'remove':
        $row = new Playertool( $database );
        $row->bind( $_POST );
        $row->set( 'project_id', $project->id );
        $row->set( 'team_id', $team->id );
        for ($x=0;$x<count($cid);$x++)
        {
          $row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'back':
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=teamtool");
        break;
      
      case 'assign':
      unset($w, $y, $player1);
        $query = sprintf("SELECT p.id, p.lastname, p.firstname, p.info
                    FROM #__joomleague_players p
               LEFT JOIN #__joomleague_playertool pt on pt.player_id = p.id
                   WHERE team_id = %s AND project_id = %s
                   ORDER BY p.lastname",$team->id, $project->id);
        $database->setQuery($query);
        //print $database->getQuery();
        $playerlist2_result = $database->loadObjectList();
        //print mysql_error();
      
        //we dont need these players in the first list
        $ids = array();
        foreach($playerlist2_result as $player){
          $ids[] = $player->id;
        }
        /*
        $query = sprintf('SELECT p.id, p.lastname, p.firstname, p.info 
                    FROM #__joomleague_players AS p 
         LEFT OUTER JOIN #__joomleague_playertool AS pt ON pt.player_id = p.id AND pt.project_id=%s
                   WHERE pt.project_id is null
                ORDER BY p.lastname',$project->id);
        */
        $query = 'SELECT p.id, p.lastname, p.firstname, p.info 
                    FROM #__joomleague_players AS p 
                ORDER BY p.lastname';
        $database->setQuery( $query );
        $playerlist1_result = $database->loadObjectList();
        
        $player1 = array();
        foreach($playerlist1_result as $result){
            $player1[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname,$result->firstname,$result->info)); 
        }

        //$tlist1 = mosHTML::selectList( $player1, 'list1', 'class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list1,document.adminForm.list2)" style="width:350px;"','value', 'text','');
        
        $player2 = array();
        
        if(count($playerlist2_result) > 0){
          foreach($playerlist2_result as $result){
          $player2[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)",$result->lastname,$result->firstname,$result->info));
          }
        }
        
        //$tlist2 = mosHTML::selectList( $player2, 'list2','class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list2,document.adminForm.list1)" style="width:350px"','value','text','');        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_assign_players.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
    
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ); 
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions WHERE isStaff=0 order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );

        
        $query = sprintf("SELECT count(*)
                            FROM #__joomleague_players p, #__joomleague_playertool pt 
                           WHERE p.id = pt.player_id AND pt.project_id = $project->id AND team_id = $team->id");
        $database->setQuery( $query );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
                
        #list players of a team
        $query = sprintf("SELECT p.*, pt.id AS playertoolid, pt.height, pt.weight, pt.injury AS playertoolinjury, pt.position_id, pt.injury_date AS playertoolinjury_date, 
                          pt.position_number, pt.injury_end AS playertoolinjury_end, pt.checked_out AS checked_out, u.name AS editor
                            FROM #__joomleague_players p, #__joomleague_playertool pt
                           LEFT JOIN #__users AS u ON u.id = pt.checked_out
                           WHERE p.id = pt.player_id AND pt.project_id = $project->id AND team_id = $team->id
                           ORDER BY pt.position_id, pt.position_number, p.lastname
                            LIMIT $pageNav->limitstart,$pageNav->limit");
        $database->setQuery($query);
        $rows = $database->loadObjectList();
        
//        $total = 400;
        
//        include_once( "includes/pageNavigation.php" );
//        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_playertool.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';      
        
      break;
    }
  break;
  
  case 'teamstaff':
    switch($task){
      case 'saveShort':
      for ($x=0;$x<count($cid);$x++)
        {
          $query="UPDATE #__joomleague_teamstaff_project SET 
          position_id = '".$_POST['position_id'.$cid[$x]]."'
          WHERE teamstaff_id = ".$cid[$x];
          $database->setQuery($query);
          $database->query();
        }
      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=teamstaff");
      case 'edit':
      
        $row = new TeamStaff( $database );
        $row->load( $cid[0] );
        
        $person = new Player( $database );
        $person->load($row->person_id);
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions WHERE isStaff=1 order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );
        $selectedvalue = 0;
        $position_append = '';
        if ($row->position_id > 0) $selectedvalue = $row->position_id;
        elseif ($person->default_position_id > 0) { $selectedvalue = $person->default_position_id; $position_append = '*';}
        $positionlist = mosHTML::selectList( $positions, 'position_id', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
                
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_teamstaff.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';    
        
      break;
      
      case 'saveAll':
        $tl->assignStaff( $_POST );
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'saveOne':
      case 'apply':
        $row = new TeamStaff( $database );
        $row->save($_POST, "");
        if ($task == 'saveOne') mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
        else mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act&task=edit&cid[]=$row->teamstaff_id");
      break;
      
      case 'cancel':
        $row = new TeamStaff( $database );
        $row->bind( $_POST );
        $row->checkin();
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'remove':
        $row = new TeamStaff( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
          $row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'assign':
        unset($w, $y, $player1);
        $query = sprintf("SELECT p.id, p.lastname, p.firstname, p.info
                    FROM #__joomleague_players p
               LEFT JOIN #__joomleague_teamstaff_project ts on ts.person_id = p.id
                   WHERE ts.projectteam_id = %s
                   ORDER BY p.lastname",$joomleague_team);
        $database->setQuery($query);
        //print $database->getQuery();
        $playerlist2_result = $database->loadObjectList();
        //print mysql_error();
      
        //we dont need these players in the first list
        $ids = array();
        foreach($playerlist2_result as $player){
          $ids[] = $player->id;
        }
        /*
        $query = sprintf('SELECT p.id, p.lastname, p.firstname, p.info 
                    FROM #__joomleague_players AS p 
         LEFT OUTER JOIN #__joomleague_playertool AS pt ON pt.player_id = p.id AND pt.project_id=%s
                   WHERE pt.project_id is null
                ORDER BY p.lastname',$project->id);
        */
        $query = 'SELECT p.id, p.lastname, p.firstname, p.info 
                    FROM #__joomleague_players AS p 
                ORDER BY p.lastname';
        $database->setQuery( $query );
        $playerlist1_result = $database->loadObjectList();
        
        $player1 = array();
        foreach($playerlist1_result as $result){
        	  if ( !in_array($result->id, $ids) )
             $personOut[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)", $result->lastname,$result->firstname,$result->info)); 
        }

        //$tlist1 = mosHTML::selectList( $player1, 'list1', 'class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list1,document.adminForm.list2)" style="width:350px;"','value', 'text','');
        
        $player2 = array();
        
        if(count($playerlist2_result) > 0){
          foreach($playerlist2_result as $result){
            $personIn[] = mosHTML::makeOption($result->id, sprintf("%s, %s (%s)",$result->lastname,$result->firstname,$result->info));
          }
        }
        
        //$tlist2 = mosHTML::selectList( $player2, 'list2','class="inputbox" size="20" multiple="multiple" onDblClick="move(document.adminForm.list2,document.adminForm.list1)" style="width:350px"','value','text','');        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_assign_teamstaff.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
    
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ); 
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions WHERE isStaff=1 order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );

        
        $query = sprintf("SELECT count(*)
                            FROM #__joomleague_players p, #__joomleague_teamstaff_project ts 
                           WHERE p.id = ts.person_id AND ts.projectteam_id = $joomleague_team");
        $database->setQuery( $query );
        if ( !$total = $database->loadResult() ) {
        }
          
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
                
        #list players of a team
        $query = sprintf("SELECT p.id, p.firstname,lastname,default_picture,default_position_id, 
                           ts.teamstaff_id, ts.projectteam_id, ts.position_id,  
                           ts.checked_out, ts.checked_out_time, u.name AS editor
                           FROM #__joomleague_players p, #__joomleague_teamstaff_project ts
                           LEFT JOIN #__users AS u ON u.id = ts.checked_out
                           WHERE p.id = ts.person_id AND ts.projectteam_id = $joomleague_team
                           ORDER BY ts.position_id, p.lastname
                           LIMIT $pageNav->limitstart,$pageNav->limit");
        $database->setQuery($query);
        $rows = $database->loadObjectList();
//        $total = 400;
        
//        include_once( "includes/pageNavigation.php" );
//        $pageNav = new mosPageNav( $total, $limitstart, $limit  );            
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_teamstaff.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';      
        
      break;
    }
  break;
  
  case 'players':
    
    //require_once 'components/com_joomleague/classes/class.Player.php';
    
    switch($task){
      case 'saveShort':
        for ($x=0;$x<count($cid);$x++)
        {
        	$query="UPDATE #__joomleague_players SET 
        	firstname = '".$_POST['firstname'.$cid[$x]]."', 
        	lastname = '".$_POST['lastname'.$cid[$x]]."',
        	birthday = '".$_POST['birthday'.$cid[$x]]."',
        	default_position_id = '".$_POST['default_position_id'.$cid[$x]]."', 
        	default_weight = '".$_POST['default_weight'.$cid[$x]]."', 
        	default_height = '".$_POST['default_height'.$cid[$x]]."',
        	nation = '".$_POST['nation'.$cid[$x]]."',
        	checked_out = 0,
        	checked_out_time = 0 
        	WHERE id = ".$cid[$x];
        	$database->setQuery($query);
        	$database->query();
        }
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=players");
        break;
      case 'new':
      case 'edit':
        $row = new Player( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && $my->id != $project->joomleague_admin &&
         $my->id != $project->joomleague_editor && $my->usertype != 'Administrator' && $my->usertype != 'Super Administrator') {
          
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $selectedvalue=$row->nation;
        $countrycode=explode("_", _JL_LOCALE);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3 FROM #__joomleague_countries ORDER BY published DESC, countries_name, countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'nation', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );

          $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
          $positions = array_merge( $positions, $database->loadObjectList() );
          $positionlist = mosHTML::selectList( $positions, 'default_position_id', 'class="inputbox" size="1"','value', 'text', $row->default_position_id );
        if (is_null($row->nation)||$row->nation==0) $clist.=_JL_ADMIN_SELECT_COUNTRY_HINT;
        
        $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_USER );
        $database->setQuery( "SELECT id AS value, name AS text 
                                FROM #__users " );
        $users = array_merge( $users, $database->loadObjectList() );

        $user_list = mosHTML::selectList( $users, 'jl_user_id', 'class="inputbox" size="1"','value', 'text', $row->jl_user_id );
        unset( $users );
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_players.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
      
      case 'save':
      case 'apply':
        $row = new Player( $database );
	      $row->save($_POST, "");
	      if ($task == 'apply') mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act&task=edit&cid[0]=$row->id" );
        else mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Player( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;

      case 'remove':
        $row = new Player( $database );
        $row->bind( $_POST );
        $res = true;
        for ($x=0;$x<count($cid);$x++)
        {
        	$res = $res && $row->delete($cid[$x]);
        }
        if ($res) {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
        }
        else {
          mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act", $row->getError());
        }
      break;      
      
      default:
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.lastname) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_players AS a"
                          . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "")
        );
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_players AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out"
                           . (count( $where ) ? " WHERE " . implode( ' AND ', $where ) : "").
                          " ORDER BY a.lastname
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();
        $positions[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_POSITION );
        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_positions order by ordering");
        $positions = array_merge( $positions, $database->loadObjectList() );
        $selectedvalue=0;
        
        $countrycode=explode("_", _JL_LOCALE);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3
        FROM #__joomleague_countries ORDER BY published DESC, countries_name, countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        	//	if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}  

        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_players.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
  
  break;
  
  case 'playgrounds':
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Playground( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect( JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }

        // prepare clubselector
        $clubs[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_CLUB );

        $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_clubs ORDER BY name");
        $clubs = array_merge( $clubs, $database->loadObjectList() );
        $clist = mosHTML::selectList( $clubs, 'club_id', 'class="inputbox" size="1"','value', 'text', $row->club_id );

				$selectedvalue=$row->country;
				$countrycode=explode("_", _JL_LOCALE);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$value=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		$value=$result->countries_localname;
        		if (is_null($row->country)) $selectedvalue=$result->countries_id;
        	}
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $countrylist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_playgrounds.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new Playground( $database );
	      $row->save($_POST, "");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Playground( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Playground( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;         
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_playgrounds AS a");
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a. * , u.name AS editor, c.name AS club
                                FROM #__joomleague_playgrounds AS a
                                LEFT JOIN #__users AS u ON u.id = a.checked_out
                                LEFT JOIN #__joomleague_clubs AS c ON c.id = a.club_id
                            ORDER BY a.name
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_playgrounds.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
  
  break;

  case 'referees':
    
    //require_once 'components/com_joomleague/classes/class.Player.php';
    
    switch($task){
      
      case 'new':
      case 'edit':
        $row = new Referee( $database );
        $row->load( $cid[0] );
        
        if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
          mosRedirect(JL_ADMIN_COMPONENT_LINK, 'This Item has been checked out');
        }
        
        if ($cid[0]) {
          $row->checkout( $my->id );
        }
        $selectedvalue=$row->nation;
        $countrycode=explode("_", _JL_LOCALE);
        $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_NATIONALITY );
        $database->setQuery( "SELECT countries_id, countries_name, countries_localname, countries_iso_code_2, countries_iso_code_3 FROM #__joomleague_countries ORDER BY countries_iso_code_3");
        $results = $database->loadObjectList();
        foreach ($results AS $result) {
        	$namevalue=$result->countries_name;
        	if (isset($country[$result->countries_iso_code_3])) $namevalue=$country[$result->countries_iso_code_3];
        	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
        		if (is_null($row->nation)||$row->nation==0) $selectedvalue=$result->countries_id;
        		$namevalue=$result->countries_localname;
        	}
        	$value=$result->countries_iso_code_3." ($namevalue)";
        	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
				}
        $clist = mosHTML::selectList( $countries, 'nation', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
        if (is_null($row->nation)||$row->nation==0) $clist.=_JL_ADMIN_SELECT_COUNTRY_HINT;
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_referees.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';   
        
      break;
      
      case 'save':
        $row = new Referee( $database );
	      $row->save($_POST, "");
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;
      
      case 'cancel':
        $row = new Referee( $database );
	      $row->bind( $_POST );
	      $row->checkin();
	      mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=$act" );
      break;
      
      case 'remove':
        $row = new Referee( $database );
        $row->bind( $_POST );
        for ($x=0;$x<count($cid);$x++)
        {
        	$row->delete($cid[$x]);
        }
        mosRedirect(JL_ADMIN_COMPONENT_LINK."&act=$act");
      break;         
      
      default:
        
        $limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', _JL_LIST_LIMIT );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        
        $search = $mainframe->getUserStateFromRequest( "search{$option}{$act}", 'search', '' );
	      $search = $database->getEscaped( trim( strtolower( $search ) ) );
        
        $where = array();
        if ($search) {
            $where[] = "LOWER(a.lastname) LIKE '$search%'";
	      }
        
        $database->setQuery( "SELECT count(*) FROM #__joomleague_referees AS a". (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : ""));
        $total = $database->loadResult();
        
        include_once( "includes/pageNavigation.php" );
        $pageNav = new mosPageNav( $total, $limitstart, $limit  );
        
        $database->setQuery( "SELECT a.*, u.name AS editor
                                FROM #__joomleague_referees AS a
                           LEFT JOIN #__users AS u ON u.id = a.checked_out"
                           . (count( $where ) ? "\nWHERE " . implode( ' AND ', $where ) : "").
                           " ORDER BY a.lastname
                               LIMIT $pageNav->limitstart,$pageNav->limit");
        $rows = $database->loadObjectList();        
        
        $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_referees.tpl.php';    
        require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
        
      break;
    }
    break;
  
  case 'JLexport':
    jlexport($project);
    break;
    
  case 'positionEventType':
  	managePositionEventType($task);	
    break;
    
  case 'playersimport':
  	managePlayersImport($task);	
    break;
}
}

function clubs_edit( $cid , $task ) {
  global $database, $my;
  
  $row = new Club( $database );
  $row->load( $cid[0] );
  
  if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
    mosRedirect( JL_ADMIN_COMPONENT_LINK);
  }
  
  if ($cid[0]) {
    $row->checkout( $my->id );
  }
  $selectedvalue=$row->country;
  $countrycode=explode("_", _JL_LOCALE);
  $countries[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_COUNTRY );
  $database->setQuery( "SELECT countries_id, countries_name, countries_iso_code_2, countries_iso_code_3, countries_localname FROM #__joomleague_countries WHERE published = 1");
  $results = $database->loadObjectList();
  foreach ($results AS $result) {
  	if (strtoupper($result->countries_iso_code_2)==strtoupper($countrycode[0])) {
  		if (is_null($row->country)) $selectedvalue=$result->countries_id;
  		$value=$result->countries_localname;
  	}
  	else {
  		if (isset($country[$result->countries_iso_code_3])) $value=$country[$result->countries_iso_code_3];
  		else $value=$result->countries_name;
  	}
  	$countries[] = mosHTML::makeOption( $result->countries_id, "$value" );
	}
  $clist = mosHTML::selectList( $countries, 'country', 'class="inputbox" size="1"','value', 'text', $selectedvalue );
  if (is_null($row->country)) $clist.="<b>"._JL_ADMIN_NOT_USED."</b>";
  
  // select list for admin
  $users[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_ADMIN );
  $database->setQuery( "SELECT id AS value, name AS text 
                          FROM #__users ORDER BY gid DESC" );
  $users = array_merge( $users, $database->loadObjectList() );

  $user_list = mosHTML::selectList( $users, 'admin', 'class="inputbox" size="1"', 'value', 'text', $row->admin );
  unset( $users );
  
  // select list for playgrounds
  $playgrounds[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PLAYGROUND );  
  $database->setQuery( "SELECT id AS value, name AS text FROM #__joomleague_playgrounds ORDER BY name");  
  $playgrounds = array_merge( $playgrounds, $database->loadObjectList() );
  $playgroundslist = mosHTML::selectList( $playgrounds, 'standard_playground', 'class="inputbox" size="1"','value', 'text', $row->standard_playground );
  unset( $playgrounds );       

  // select list of images from placeholder folder
  $images[] = mosHTML::makeOption( '', _JL_ADMIN_SELECT_PICTURE );
  if ( $dp = opendir( _JOOMLA_JL_PATH . '/images/joomleague/teams' ) )
  {
  	$list = array();
  	while ( ( $file = readdir( $dp ) ) !== false )
  	{
  		if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $file ) ) {
  			$list[] = $file;
  		}
  	}
  	if ( count($list) ) 
  	{
  		sort( $list );
	  	foreach ($list as $l) {
	  		$images[] = mosHTML::makeOption( '/images/joomleague/teams/'.$l, $l );
	  	}
  	}
  	closedir($dp);
  }
  $logo_big_list = mosHTML::selectList( $images, 'selbig', 
      'class="inputbox" size="1" onchange="src=document.getElementById(\'logo_big\');src.value=this.value;updateClubLogo(\'big\', src);"',
      'value', 'text', $row->logo_big );
  $logo_middle_list = mosHTML::selectList( $images, 'selmedium', 'class="inputbox" size="1" onchange="src=document.getElementById(\'logo_middle\');src.value=this.value;updateClubLogo(\'medium\', src);"', 'value', 'text', $row->logo_middle );
  $logo_small_list = mosHTML::selectList( $images, 'selsmall', 'class="inputbox" size="1" onchange="src=document.getElementById(\'logo_small\');src.value=this.value;updateClubLogo(\'small\', src);"','value', 'text', $row->logo_small );
  unset( $images );
  
  $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_clubs.tpl.php';    
  require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php';
} 

function showconfig($option) {
	global $database, $mainframe, $jlgConfig;

	$configfile = JL_ADMIN_PATH."/jlgconfig.php";
	@chmod ($configfile, 0766);

	if (!is_callable(array("JFile","write")) || ($mainframe->getCfg('ftp_enable') != 1)) {
		$permission = is_writable($configfile);
		if (!$permission) {
			echo "<center><h1><font color=red>Warning...</font></h1><BR>";
			echo "<B>Your config file: $configfile <font color=red>is not writable</font></b><BR>";
			echo "<B>You need to chmod this to 766 in order for the config to be updated</B></center><BR><BR>";
		}
	}
	
	$lists = array();	
	// make a standard yes/no list
	$yesno = array();
	$yesno[] = mosHTML::makeOption( '0', _JL_NO );
	$yesno[] = mosHTML::makeOption( '1', _JL_YES );
	
  $lists['club_info_update_notify'] = mosHTML::selectList( $yesno, 'cfg_club_info_update_notify', 'class="inputbox" size="1"', 'value', 'text', $jlgConfig['club_info_update_notify'] );

  //$htmlHelper->showConfig( $jlgConfig, $lists, $option );
  $view = JL_ADMIN_TEMPLATE_PATH.'/edit_configuration.tpl.php'; 
  require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
}

function saveConfig ( $option ) {
  global $task;
  
	$configfile = JL_ADMIN_PATH."/jlgconfig.php";
	
   //Add code to check if config file is writeable.
   if (!is_callable(array("JFile","write")) && !is_writable($configfile)) {
      @chmod ($configfile, 0766);
      if (!is_writable($configfile)) {
         mosRedirect(JL_ADMIN_COMPONENT_LINK, "FATAL ERROR: Config File Not writeable" );
      }
   }

   $txt = "<?php\n";
   foreach ($_POST as $k=>$v) {
   	  if (is_array($v)) $v = implode("|*|", $v);
      if (strpos( $k, 'cfg_' ) === 0) {
         if (!get_magic_quotes_gpc()) {
            $v = addslashes( $v );
         }
		 $txt .= "\$jlgConfig['".substr( $k, 4 )."']='$v';\n";
      }
   }
   $txt .= "?>";

   if (is_callable(array("JFile","write"))) {
		$result = JFile::write( $configfile, $txt );
   } else {
		$result = false;
		if ($fp = fopen( $configfile, "w")) {
			$result = fwrite($fp, $txt, strlen($txt));
			fclose ($fp);
		}
   }
   if ($result != false) {
      if ( $task == 'apply') {
        mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=config&task=edit", "Configuration file saved" );
      }
      else {
        mosRedirect( JL_ADMIN_COMPONENT_LINK, "Configuration file saved" );
      }      
   } else {
      mosRedirect( JL_ADMIN_COMPONENT_LINK, "FATAL ERROR: File could not be opened." );
   }
}

function template_config_reset( $cid ) {
  global $database , $option, $project;
	$ids = implode(',', $cid);
	$query="DELETE FROM #__joomleague_template_config WHERE id IN (".$ids.") AND project_id = ".$project->id;
	$database->setQuery($query);
  $database->query();
	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config" );
}

function template_config_apply() {
  global $database, $option, $my;
  $string="";
	foreach ($_POST AS $key=>$value) {
		if ($key !="option" && $key !="act" && $key !="task" && $key !="id") {
			$value= ereg_replace("(\r\n|\n|\r)", "", $value);
			$string.= "$key=$value\n";
		}
	} 
	$query="UPDATE #__joomleague_template_config SET params = '".$string."' WHERE id = ".$_POST['id'];
	$database->setQuery($query);
  $database->query();
	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config&task=edit&cid[0]=".$_POST['id'] );
}

function template_config_save() {
  global $database, $my;
  $string="";
	foreach ($_POST AS $key=>$value) {
		if ($key !="option" && $key !="act" && $key !="task" && $key !="id") {
			$value= ereg_replace("(\r\n|\n|\r)", "", $value);
			$string.= "$key=$value\n";
		}
	} 
	$query="UPDATE #__joomleague_template_config SET params = '".$string."' WHERE id = ".$_POST['id'];
	$database->setQuery($query);
  $database->query();
	$row = new TemplateConfig($database);
  $row->bind( $_POST );
  $row->checkin();
  //define $msg;
  $msg = '';
	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config" , $msg );//msg not defined !
}

/**
 * displays template for editing
 *
 * @param int $cid template row in database for project
 */
function template_config_edit($cid) {
  global $database, $my, $project;
  $row = new TemplateConfig($database);
	$row->load($cid[0]);

  if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
    mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config");
  }

  if ($cid[0]) {
     $row->checkout( $my->id );
  }
  
	if (substr(_JL_LANG, 0, 6) == "german") $langfolder = "german";
	else $langfolder = _JL_LANG;
	
  // first check custom template folder if template is not default
  if ($project->template != "default") {
      if (is_dir(JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/'.$langfolder)) {
        $xmlfile = JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/'.$langfolder.'/'.$row->template.'.jml';
      }
      else if (is_dir(JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/english')) {
        $xmlfile = JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/english/'.$row->template.'.jml';
      }
      if (!isset($xmlfile) || !file_exists($xmlfile)) {
      	if (is_dir(JL_CONFIG_PATH.'/'.$langfolder)) {
			  // xml file for module
			    $xmlfile = JL_CONFIG_PATH.'/'.$langfolder.'/'.$row->template.'.jml';
			  }
			  else $xmlfile = JL_CONFIG_PATH.'/english/'.$row->template.'.jml';
      }
  }
  else if (is_dir(JL_CONFIG_PATH.'/'.$langfolder)) {
	// xml file for module
		$xmlfile = JL_CONFIG_PATH.'/'.$langfolder.'/'.$row->template.'.jml';
	}
	else $xmlfile = JL_CONFIG_PATH.'/english/'.$row->template.'.jml';
	
	//echo $xmlfile;
	
  $xml = new Xml;
	$iso = split( '=', _ISO );
	
	$out = $xml->parse($xmlfile, 'FILE', $iso[1]);

	$params = explode("\n", $row->params);

          foreach($params AS $param) {
              if ($param!='') {
		  list ($name, $value)= explode("=", $param);
		  $configvalues[$name]=$value;
		}
	}

	//echo "</pre></div>";
	$view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_templates.tpl.php'; 
  require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
} 


function template_config_cancel() {
  global $database, $my;  
	$row = new TemplateConfig($database);
  $row->bind( $_POST );
  $row->checkin();
	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config" );
}

function template_config_import($project_id) {
  global $database;  
	if ( intval($_POST['templateImport']) ) {
    $template = new TemplateConfig($database);
    $template->load( intval($_POST['templateImport']) );
    //print_r($template);exit;
    $template->set('project_id', $project_id);
    $template->set('id', NULL);
    if ( !$template->store() ) echo "Error while importing template".$database->getErrorMsg()."<br/>";
  }
	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=template_config" );
}

function template_config_show() {
  global $database;
  global $project;
  
  if ( $project->master_template == 0) {
    checkTemplateList( $project );
  }
  else 
  {
  	// get list of templates we can import from master
    $database->setQuery("SELECT name FROM #__joomleague WHERE id=$project->master_template");
    $master_name = $database->loadResult();
    
    $master_tpl[] = mosHTML::makeOption( '0', '&nbsp;' );
    $query="SELECT id AS value, template AS text FROM #__joomleague_template_config 
                    WHERE project_id = $project->master_template";
  	$database->setQuery($query);
    $master_tpl = array_merge( $master_tpl, $database->loadObjectList() );
  
    $master_tpl_list = mosHTML::selectList( $master_tpl, 'templateImport', 'class="inputbox" size="1"','value', 'text', 0 );
    unset( $master_tpl );
  }
    
  $query="SELECT jtc.*, a.joomleague_admin, u.name AS editor
                FROM #__joomleague_template_config AS jtc
           LEFT JOIN #__joomleague AS a ON a.id = jtc.project_id
           LEFT JOIN #__users AS u ON u.id = jtc.checked_out
               WHERE jtc.project_id = $project->id
        ORDER BY published, jtc.title ASC";      
  
  $database->setQuery($query);
  $templates = $database->loadObjectList();
  
  $view = JL_ADMIN_TEMPLATE_PATH.'/edit_list_templates.tpl.php'; 
  require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
}

/**
 * Checks that the template list is complete for the project.
 * If not, add the missings templates
 *
 * @param object $project
 */
function checkTemplateList( $project )
{
	  global $database;

	  // no need to check if there is a master template
	  if ( $project->master_template ) { return; } 
	  
    if (substr(_JL_LANG, 0, 6) == "german") $langfolder = "german";
    else $langfolder = _JL_LANG;
    
    // first check custom template folder if template is not default
    if ($project->template != "default") {
      if (is_dir(JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/'.$langfolder)) {
        $xmldirs[] = JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/'.$langfolder;
      }
      else if (is_dir(JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/english')) {
        $xmldirs[] = JL_FRONTEND_PATH.'/frontend/'.$project->template.'/config_xml/english';
      }
    }
    if (is_dir(JL_CONFIG_PATH.'/'.$langfolder)) {
      $xmldirs[] = JL_CONFIG_PATH.'/'.$langfolder;
    }
    else $xmldirs[] = JL_CONFIG_PATH.'/english';
    
    foreach ($xmldirs as $xmldir) 
    {
      if ($handle = opendir($xmldir)) 
      {
        /* check that each xml template has a corresponding record in the 
        database for this project. If not, create the rows with default values
        from the xml file */
        while ( $file = readdir($handle) ) 
        {
          if ( $file != "." && $file != ".." && strtolower(substr($file, -3))=='jml') 
          {
            $template=substr($file, 0, (strlen($file)-4));
            $query="SELECT id FROM #__joomleague_template_config WHERE project_id = $project->id
                                                                    AND template = '".$template."'";
            $database->setQuery($query);
            if ($id=$database->loadResult()) 
            {
              //template present in db for this project, check values are up to date              
            }
            else 
            {
              //template not present, create a row with default values
              $xml = new Xml;
              $out = $xml->parse($xmldir."/".$file, 'FILE', substr(_ISO,8) );
              $temp='';
              foreach ( $out["params"]["param-ATTR"] as $param )
              {
                if ($param["type"]!="spacer") $temp.=$param["name"]."=".$param["default"]."\n";
              }
              $query = "INSERT INTO #__joomleague_template_config (template, func, title, params, project_id) VALUES
                    ('".$template."', '".$out["func"]."', '".$out["name"]."', '".trim($temp)."', ".$project->id.")";
              $database->setQuery($query);
              //echo error, allows to check if there is a mistake in the template file
              if (!$database->query()) echo "<b>Error in $template:</b> ".$database->getErrorMsg().'<br/>';
            }
          }
        }
        closedir($handle);
      }
    }
}

function jlImport() {
	  global $database;
    $view = JL_ADMIN_TEMPLATE_PATH.'/edit_form_jl_import.tpl.php';
    require JL_ADMIN_TEMPLATE_PATH.'/view.tpl.php'; 
}

function jlexport($project) {
      if ($project) {
        $output = '<?xml version="1.0" encoding="'.substr(_ISO,8).'"?>'."\n";
        $output.= $project->toXML();
        $file = fopen(JL_ADMIN_PATH.'/imports/project_export.jlg','w+');
        if (fwrite($file, $output ) === FALSE) {
          echo "Cannot write to file ($filename)";
          exit;
        }
        fclose($file);
        mosRedirect(_JOOMLA_JL_LIVE_SITE.'/administrator/components/com_joomleague/imports/project_export.jlg');
      }
      else {
        mosRedirect( JL_ADMIN_COMPONENT_LINK );
      }
    }
    
function copyProject( $post ) 
{
	global $database;
	
  $name = mosGetParam($_POST, "name","copy");
  $league_id = mosGetParam($_POST, "league_id", 0);
  $season_id = mosGetParam($_POST, "season_id", 0);
  $old_id = mosGetParam($_POST, "old_id", 0);
  
  //check project unicity if season and league are not both new
  if ( $league_id && $season_id) {
	  $query = "SELECT id FROM #__joomleague
	              WHERE name = '$name'
	              AND league_id = '$league_id'
	              AND season_id = '$season_id'";
	  $database->setQuery($query);
	  $database->query($query);
	  $num = $database->getAffectedRows();
	  if ($num>0) {
	  	mosRedirect( JL_ADMIN_COMPONENT_LINK."&act=projects&task=copy&cid[0]=".$old_id, "This project already exists" );
	    return;
	  }
  }

  $project = new Joomleague($database);
  $project->bind($_POST);

  //create new league if requested
  if ( mosGetParam($_POST, "newLeagueCheck", 0) ) {
  	$query = "SELECT MAX(ordering) AS ordering FROM #__joomleague_leagues";
  	$database->setQuery($query);
  	$ordering = $database->loadResult()+1;

  	$newLeague = mosGetParam($_POST, "leagueNew", "new league");
    
  	$league = new League($database);
  	$league->set('name', $newLeague);  	
    $league->set('ordering', $ordering);
    $league->store();
    $league_id = $league->get('id');
    //update project object
    $project->set('league_id', $league_id);
  }
  //create new season if requested
  if ( mosGetParam($_POST, "newSeasonCheck", 0) ) {
    $query = "SELECT MAX(ordering) AS ordering FROM #__joomleague_seasons";
    $database->setQuery($query);
    $ordering = $database->loadResult()+1;

    $newSeason = mosGetParam($_POST, "seasonNew", "new season");
    
    $season = new Season($database);
    $season->set('name', $newSeason);   
    $season->set('ordering', $ordering);
    $season->store();
    $season_id = $season->get('id');
    //update project object
    $project->set('season_id', $season_id);
  }
  //TODO: save fav team too...
  //save project
  $project->store();
  $id = $project->get('id');
  
  //copy divisions
  $source_to_copy_division = Array( "0" => 0 );
  $database->setQuery("SELECT * FROM #__joomleague_divisions WHERE project_id=$old_id AND parent_id=0");
  if ( $results = $database->loadAssocList() ) {
  	foreach($results as $result) {
      $division = new LeagueDivision($database);
      $division->bind($result);
      $division->set('id', NULL);
      $division->set('project_id', $id);
      if ( $division->store() ) {
      	$source_to_copy_division[$result['id']] = $division->get('id');
      	//subdivisions
      	$database->setQuery("SELECT * FROM #__joomleague_divisions WHERE project_id=$old_id AND parent_id=".$result['id']);		   
        if ( $subs = $database->loadAssocList() ) {
        	foreach ($subs as $sub) {
        		$subdiv = new LeagueDivision($database);
        		$subdiv->bind( $sub );
        		$subdiv->set('id', NULL);
        		$subdiv->set('project_id', $id);
        		$subdiv->set('parent_id', $division->get('id')); 
        		if ( $subdiv->store() ) 
        		  $source_to_copy_division[$sub['id']] = $subdiv->get('id');       		
        	}
        }
      }
  	}
  }
  
  //copy teams
  $database->setQuery("SELECT * FROM #__joomleague_team_joomleague WHERE project_id=$old_id");
  if ( $results = $database->loadAssocList() ) {
    foreach($results as $result) {
      $p_team = new TeamTool($database);
      $p_team->bind($result);
      $p_team->set('id', NULL);
      $p_team->set('project_id', $id);
      $p_team->set('start_points', 0);
      $p_team->set('division_id', $source_to_copy_division[$result['division_id']]);
      if ( !$p_team->store() ) {
      	echo $database->getErrorMsg();
      }
    }
  }
  
  //copy players
  $database->setQuery("SELECT * FROM #__joomleague_playertool WHERE project_id=$old_id");
  if ( $results = $database->loadAssocList() ) {
    foreach($results as $result) {
      $p_player = new PlayerTool($database);
      $p_player->bind($result);
      $p_player->set('id', NULL);
      $p_player->set('project_id', $id);
      $p_player->set('injury', 0);
		  $p_player->set('injury_date', 0);
		  $p_player->set('injury_end', 0);
		  $p_player->set('injury_detail', '');
		  $p_player->set('suspension', 0);
		  $p_player->set('suspension_date', 0);
		  $p_player->set('suspension_end', 0);
		  $p_player->set('suspension_detail', '');
      if ( !$p_player->store() ) {
        echo $database->getErrorMsg();
      }
    }
  }
  
  //copy xml templates settings
  $query = "SELECT id FROM #__joomleague_template_config WHERE project_id=$old_id";
  $database->setQuery($query);
  if ( $templates = $database->loadObjectList() ){
  	$template = new TemplateConfig($database);  
	  foreach ($templates AS $tp) {
	  	$template->load($tp->id);
	  	$template->set( 'project_id', $proj->id );
	  	$template->set( 'id', NULL );
	  	$template->store();
	  }
  }
}

function managePositionEventType($task)
{
	global $my, $mainframe, $mosConfig_list_limit, $option, $act, $database, $mosConfig_live_site;
  global $joomleague, $joomleague_version, $cid, $joomleague_team, $round;
  
  $positionId = mosGetParam( $_REQUEST, 'posId', 0 );
	//$database = &$joomleague->_db;
	
	switch ($task) {
		case 'add' :
		case 'edit' :
			$position = new Position($database);
			$position->load($positionId);
			
			$row = new PositionEventType( $database );
			if ($cid[0]) $row->load( $cid[0] );
			if ($row->checked_out && $row->checked_out <> $my->id && strtolower($my->usertype) != 'super administrator') {
				mosRedirect( "index2.php?option=$option");
			}

			if ($cid[0]) {
				$row->checkout( $my->id );
			}

			$query = "SELECT id AS value, name AS text
                    FROM #__joomleague_eventtypes
                    ORDER BY name";
			$database->setQuery($query);
			$eventtype[] = mosHTML::makeOption( 0, 'Select Event type' );
			if ($result = $database->loadObjectList()) {
				foreach ($result as $r) {
					$eventtype[] = mosHTML::makeOption( $r->value, $r->text );
				}
			}
			$eventList = mosHTML::selectList( $eventtype, 'eventtype_id', 'class="inputbox" size="1"','value', 'text', intval( $row->eventtype_id ) );


			$order = mosGetOrderingList( "SELECT pet.ordering AS value, et.name AS text
                                    FROM #__joomleague_position_eventtype AS pet
                                    INNER JOIN #__joomleague_eventtypes AS et ON pet.eventtype_id = et.id
                                    WHERE pet.position_id = $positionId
                                    ORDER BY ordering");
			$list = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"','value', 'text', $positionId );

			$view = 'components/com_joomleague/templates/edit_form_position_eventtype.tpl.php';
			$jl_version=$joomleague_version;
			require 'components/com_joomleague/templates/view.tpl.php';

			break;

		case 'addAll':
			// get max ordering for events assigned to this position
			$query = ' SELECT MAX(ordering) ' 
			       . ' FROM #__joomleague_position_eventtype '
			       . ' WHERE position_id =  ' . $positionId;
			$database->setQuery($query);
			$ordering_start = $database->loadResult();
			if ( !$ordering_start ) {
				$ordering_start = 1;
			}
			else {
        $ordering_start++;
      }
      
      // get all events id not yet assigned to the position
      $query = ' SELECT ev.id ' 
             . ' FROM #__joomleague_eventtypes AS ev'
             . ' WHERE NOT EXISTS (
                  SELECT *
                  FROM #__joomleague_position_eventtype AS pev
                  WHERE ev.id = pev.eventtype_id AND pev.position_id = ' . $positionId
             . ' ) ';
      $database->setQuery($query);
      $ids = $database->loadResultArray();
      
      // add the events
      if ( count( $ids ) ) 
      {
        foreach ($ids as $event_id)
        {
        	$pev = new PositionEventType( $database );
        	$pev->eventtype_id = $event_id;
        	$pev->position_id = $positionId;
        	$pev->ordering = $ordering_start++;
        	
        	$pev->store();
        }
      }
			mosRedirect( "index2.php?option=$option&act=$act&posId=$positionId");
			break;
			
		case 'save':
			$row = new PositionEventType( $database );
			$row->save($_POST, "");
			$row->updateOrder();
			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id");
			break;

		case 'remove':
			$row = new PositionEventType( $database );
			$row->bind( $_POST );
			for ($x=0;$x<count($cid);$x++)
			{
				$row->delete($cid[$x]);
			}
			mosRedirect("index2.php?option=$option&act=$act&posId=$positionId");
			break;

		case 'cancel':
			$row = new PositionEventType( $database );
			$row->bind( $_POST );
			$row->checkin();
			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id");
			break;

		case 'orderup':
			$row = new PositionEventType( $database );
			$row->load( $cid[0] );
			$row->move( -1, "position_id=$row->position_id" );

			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id" );
			break;

		case 'orderdown':
			$row = new PositionEventType( $database );
			$row->load( $cid[0] );
			$row->move( 1, "position_id=$row->position_id" );

			mosRedirect( "index2.php?option=$option&act=$act&posId=$row->position_id" );
			break;
    
		case 'back':
			mosRedirect( "index2.php?option=$option&act=positions" );
			break;	
			
		default:

			$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
			$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

			$database->setQuery( "SELECT count(*) FROM #__joomleague_position_eventtype AS a");
			$total = $database->loadResult();

			$positionId = mosGetParam( $_REQUEST, 'posId', 0 );
      $position = new Position($database);
      $position->load($positionId);

			include_once( "includes/pageNavigation.php" );
			$pageNav = new mosPageNav( $total, $limitstart, $limit  );

			$database->setQuery( "SELECT pet.position_eventtype_id as id, 
			                             pet.checked_out, pet.checked_out_time, pet.ordering,
			                             et.name, u.name AS editor
                             FROM #__joomleague_position_eventtype AS pet
                             LEFT JOIN #__users AS u ON u.id = pet.checked_out
                             LEFT JOIN #__joomleague_eventtypes AS et ON et.id = pet.eventtype_id
                             WHERE pet.position_id = $positionId
                              ORDER BY pet.ordering
                                 LIMIT $pageNav->limitstart,$pageNav->limit");
			$rows = $database->loadObjectList();
			//print_r($rows);exit;

			$view = 'components/com_joomleague/templates/edit_list_position_eventtypes.tpl.php';
			$jl_version=$joomleague_version;
			require 'components/com_joomleague/templates/view.tpl.php';

			break;
	}
}

function managePlayersImport($task)
{
  
}
?>
